// 临时缓存
// 当前项目下面的设备清单服务费用总额总和
let total_fwamt = 0
// 当前项目下的其他合同的金额总额
let total_cnt_amt = 0
// 可用金额
let DouDuoYvLe = 0
function AllReady() {


    var mstform = Ext.getCmp("CntM4"); //获取容器
    var tabPanel = Ext.getCmp("tabPanel");
    addTabs(mstform, tabPanel, toolbar);

    var fb_cnt_jg = Ext.getCmp('fb_cnt_jg');
    var fb_cnt_jg_store = fb_cnt_jg.getStore();
    var toolbar = Ext.getCmp("toolbar");

    var PhidDept = mstform.queryById("PhidDept"); //获取字段
    var user_product_line = mstform.queryById("user_product_line");
    var PhidPc = mstform.queryById("PhidPc");
    var user_pc_no = mstform.queryById("user_pc_no");
    var PhidYsfl = mstform.queryById("PhidYsfl");
    var user_regional_center = mstform.queryById("user_regional_center");
    var CntType = mstform.queryById("CntType");
    var fb_cnt_jg = Ext.getCmp("fb_cnt_jg")
    console.log(`测试自定义`,fb_cnt_jg);
    console.log(`测试自定义`,fb_cnt_jg.queryById("phid_item"));

    if (otype == "add") {
        PhidYsfl.setValue("14");
        BatchBindCombox([PhidYsfl]);
    }

    if (otype == 'edit' || otype == 'view') {

        execServer('GetJgInnfo', { cnt: busid }, function (res) {
            console.log('甲供物料',res, busid);  // 打印整个响应对象以便调试
            if (res.count!==0 && res.status === 'success' && res.data) {
                try {
                    // 将data字符串解析为JavaScript对象
                    const parsedData = JSON.parse(res.data);

                    if (Array.isArray(parsedData)) {
                        var arr = [];
                        for (let i = 0; i < res.count; i++) {
                            const record = parsedData[i].extendObjects;  // 从extendObjects中获取数据
                            arr.push({
                                phid: record.phid,
                                mstphid: record.mstphid,
                                phid_item: record.phid_item,
                                phid_itemname: record.itemname,
                                msunit: record.msunit,
                                msunit_name: record.msname,
                                prc_vat: record.prc_vat,
                                bzshl: record.bzshl,
                                htshl: record.htshl,
                                remarks: record.remarks,

                            });
                        }
                        // 插入数据到存储
                        fb_cnt_jg_store.insert(fb_cnt_jg_store.getCount(), arr);
                    } else {
                        console.error("Unexpected data format, expected an array:", parsedData);
                    }
                } catch (error) {
                    console.error("Error parsing JSON:", error);
                }
            } else {
                console.error("Unexpected response format or status:", res);
            }
        });

    }


    const _arr = ["CurrType", "ExchRate", "PhidYsfl", "Iscb"];
    _arr.forEach((item) => {
        mstform.getItem(item).setVisible(false);
    });
    // 选择tabs触发
    PhidPc.addListener("helpselected", function () {
        getProjectInfo();
        getEqSumInfoByPhid_pc();
        getCntMSumInfoByPhid_pc()
    });
    mstform.getItem("user_taxrate").addListener("change", function (editor, e) {
        console.log(
            `监听主表编辑`,
            e,
            Number(mstform.getItem("CntSumVatFc").getValue()) * Number(e)
        );
        mstform
            .getItem("CntSumFc")
            .setValue(
                Number(mstform.getItem("CntSumVatFc").getValue()) * Number(e)
            );
    });


    getProjectInfo();
    function getProjectInfo() {
        if (!PhidPc.getValue()) return;
        execServer(
            "getPtInfoByPhid",
            { phid: PhidPc.getValue() },
            function (res) {
                if (res.count == 0) return;
                const _data = JSON.parse(res.data)[0].extendObjects;
                console.log(`获取项目信息`, _data);
                PhidDept.setValue(_data.org_phid);
                user_regional_center.setValue(_data.regional_center_phid);
                user_product_line.setValue(_data.midwife_phid);
                user_pc_no.setValue(_data.pc_no);
                BatchBindCombox([PhidDept]);
                BatchBindCombox([user_regional_center]);
                BatchBindCombox([user_product_line]);
            }
        );
    }
    getEqSumInfoByPhid_pc();
    // 获取项目下的设备清单服务费总额(使用前提：必须是服务外包免费类型的合同)
    function getEqSumInfoByPhid_pc() {
        setTimeout(()=>{
            console.log(`合同类型`, CntType.getValue());
        if (!PhidPc.getValue() || CntType.getValue() !== "8570000000000016") return;
        execServer(
            "getEqSumInfoByPhid_pc",
            { phid_pc: PhidPc.getValue() },
            function(res) {
                console.log(`测试`,res);
                if (res.count == 0) return;
                const _data = JSON.parse(res.data)[0].extendObjects;
                console.log(_data);
                // 更新清单金额缓存和剩余金额
                total_fwamt = _data.u_total_cost_amt
                DouDuoYvLe = Number(total_fwamt - total_cnt_amt) < 0 ? 0 : Number(total_fwamt - total_cnt_amt)
            }
        );
        },500)
    }
    // 获取当前项目下的其他服务免费合同总额
    getCntMSumInfoByPhid_pc()
    function getCntMSumInfoByPhid_pc() {
        if (!PhidPc.getValue() || CntType.getValue() !== "8570000000000016") return
            execServer("getCntMSumInfoByPhid_pc", {
                phid_pc: PhidPc.getValue(),
                cnt_mode: 4,
                cnt_type: CntType.getValue()
            },
                function(res)  {
                    console.log(`测试`, res);
                    if (res.count == 0) return
                    const _data = JSON.parse(res.data)[0].extendObjects
                    // 更新合同总额缓存和剩余金额
                    total_cnt_amt = _data.cnt_sum_vat_fc
                    DouDuoYvLe = Number(total_fwamt - total_cnt_amt) < 0 ? 0 : Number(total_fwamt - total_cnt_amt)
                })
    }
}
function beforeSaveEdit() {
    if (Number(Ext.getCmp("CntM4").queryById("CntSumVatFc").getValue()) > DouDuoYvLe) {
        Ext.Msg.alert('提示', '当前合同的含税金额已超出设备清单服务费总额费用，当前合同可用金额：￥' + DouDuoYvLe)
        return false
    } else {
        return true
    }
}


//------生成主键函数(格式为日期时间毫秒+流水号)------
function generateId(sequence) {
    //获取当前时间
    const date = new Date();
    // 格式化日期为 YYMMDD
    const year = date.getFullYear().toString().slice(-2);
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const dateStr = `${year}${month}${day}`;
    // 格式化时间为 HHMMSS
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const seconds = date.getSeconds().toString().padStart(2, "0");
    const timeStr = `${hours}${minutes}${seconds}`;
    // 获取毫秒数，并确保是2位数
    const milliseconds = date
        .getMilliseconds()
        .toString()
        .padStart(3, "0")
        .slice(0, 2);
    // 格式化流水号为3位
    const sequenceStr = sequence.toString().padStart(3, "0");
    // 拼接日期、时间、毫秒和流水号
    const phid = `${dateStr}${timeStr}${milliseconds}${sequenceStr}`;
    return phid;
}

//增加表头tab页
function addTabs(mstform, tabPanel, toolbar) {
    //定义model
    var fb_cnt_jg_model = Ext.define("JdNextPlanmodel", {
        extend: "Ext.data.Model",
        fields: [
            {
                name: "phid",
                type: "bigInt",
                mapping: "phid",
            },
            {
                name: "mstphid",
                type: "bigInt",
                mapping: "mstphid",
            },
            {
                name: "phid_item",
                type: "bigInt",
                mapping: "phid_item",
            },
            {
                name: "phid_itemname",
                type: "string",
                mapping: "phid_itemname",
            },
            {
                name: "spec",
                type: "string",
                mapping: "spec",
            },
            {
                name: "msunit",
                type: "bigInt",
                mapping: "msunit",
            },
            {
                name: "msunit_name",
                type: "string",
                mapping: "msunit_name",
            },
            {
                name: "prc_vat",
                type: "string",
                mapping: "prc_vat",
            },
            {
                name: "bzshl",
                type: "string",
                mapping: "bzshl",
            },
            {
                name: "htshl",
                type: "string",
                mapping: "htshl",
            },
            {
                name: "remarks",
                type: "string",
                mapping: "remarks",
            },
        ],
    });

    //定义store
    var fb_cnt_jg_store = Ext.create("Ext.ng.JsonStore", {
        model: fb_cnt_jg_model,
    });
    //甲供物料清单 grid
    var fb_cnt_jg = Ext.create("Ext.ng.GridPanel", {
        title: "甲供材物料清单",
        id: "fb_cnt_jg",
        region: "south",
        stateful: false,
        isInit: true,
        MaxHeight: 800,
        stateId: "fb_cnt_jg", //所有单据不允许重复
        store: fb_cnt_jg_store,
        buskey: "phid", //对应的业务表主键属性
        otype: otype,
        columnLines: true,
        tbar: [{
            xtype: 'button',
            itemId: 'addrow',
            text: '增行',
            iconCls: "icon-AddRow",
            handler: function () {
                var newRecord = {
                    'phid': generateId(fb_cnt_jg_store.getCount() + 1).toString(),
                    'mstphid': busid
                    // 可以在这里添加其他初始字段
                };
                fb_cnt_jg_store.insert(fb_cnt_jg_store.getCount(), [newRecord]);
            }
        }, {
            xtype: 'button',
            itemId: 'delrow',
            text: '删行',
            iconCls: "icon-DeleteRow",
            handler: function () {
                var data = fb_cnt_jg.getSelectionModel().getSelection();
                Ext.Array.each(data, function (record) {
                    fb_cnt_jg_store.remove(record);
                });
            }
        }
        ],

        columns: [
            Ext.create("Ext.grid.RowNumberer", { text: "序号", width: 45 }),
            {
                header: Lang.pcm3_cnt_m_phid || "主键",
                dataIndex: "phid",
                itemId: "phid",
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: Lang.pcm3_cnt_m_phid || "单据主键",
                dataIndex: "mstphid",
                itemId: "mstphid",
                width: 100,
                sortable: true,
                hidden: true,
                readOnly: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "物资名称phid",
                dataIndex: "phid_item",
                itemId: "phid_item",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: "物资名称",
                dataIndex: "phid_itemname",
                width: 400,
                sortable: true,
                readOnly: false,
                mustInput: false,
                hidden: false,
                editor: {
                    xtype: "ngRichHelp",
                    valueField: "item_no",
                    displayField: "item_name",
                    listFields:
                        "m.item_no,m.item_no,item_name",
                    listHeadTexts: "物资编码,物资名称",
                    helpid: "material_supplied",
                    needBlankLine: true,
                    isInGrid: true,
                    ORMMode: false,
                    emptyText: "",
                    mustInput: false,
                    listeners: {
                        helpselected: function (obj) {
                            var data = fb_cnt_jg
                                .getSelectionModel()
                                .getSelection();
                            var oriValue = data[0].get("phid_item");
                            console.log(`无料测试`, obj);
                            data[0].set("phid_item", obj.code);
                            data[0].set("phid_itemname", obj.name);
                            data[0].set("msunit", obj.data.jldw)
                            data[0].set("msunit_name", obj.data.msname)
                            data[0].set("prc_vat", obj.data.prc_vat)
                            console.log(`选择行数据`, data);
                            var e = {};
                            e.field = "phid_item";
                            e.value = data[0].get("phid_item");
                            e.originalValue = oriValue;
                            e.record = data[0];
                            fb_cnt_jg
                                .getCellEditing()
                                .fireEvent(
                                    "edit",
                                    fb_cnt_jg.getCellEditing(),
                                    e
                                );
                        },
                    },
                },
                renderer: function (val, m) {
                    if (Ext.isObject(m)) {
                        m.style = "color:rgb(0,0,255);background-color:";
                    }
                    return val;
                },
                //, locked: true
            },
            {
                header: "单位id",
                dataIndex: "msunit",
                itemId: "msunit",
                readOnly: false,
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: "单位",
                dataIndex: "msunit_name",
                width: 100,
                sortable: true,
                readOnly: false,
                mustInput: false,
                hidden: false,
                editor: {
                    xtype: "ngRichHelp",
                    valueField: "phid",
                    displayField: "msname",
                    listFields: "msname,msunit,phid",
                    listHeadTexts: "单位编码,单位名称",
                    helpid: "pms3.msunit",
                    needBlankLine: true,
                    isInGrid: true,
                    ORMMode: false,
                    emptyText: "",
                    mustInput: false,
                    listeners: {
                        helpselected: function (obj) {
                            var data = fb_cnt_jg
                                .getSelectionModel()
                                .getSelection();
                            var oriValue = data[0].get("msunit");
                            console.log(`测试单位数据`, obj);
                            data[0].set("msunit", obj.code);
                            data[0].set("msunit_name", obj.name);
                            var e = {};
                            e.field = "msunit";
                            e.value = data[0].get("msunit");
                            e.originalValue = oriValue;
                            e.record = data[0];
                            fb_cnt_jg
                                .getCellEditing()
                                .fireEvent(
                                    "edit",
                                    fb_cnt_jg.getCellEditing(),
                                    e
                                );
                        },
                    },
                },
                renderer: function (val, m) {
                    if (Ext.isObject(m)) {
                        m.style = "color:rgb(0,0,255);background-color:";
                    }
                    return val;
                },
                //, locked: true
            },
            {
                header: "单价（含税）",
                dataIndex: "prc_vat",
                itemId: "prc_vat",
                readOnly: false,
                mustInput: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.00");
                },
            },
            {
                header: "标准损耗率",
                dataIndex: "bzshl",
                itemId: "bzshl",
                readOnly: false,
                mustInput: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.00");
                },
            },
            {
                header: "合同损耗率",
                dataIndex: "htshl",
                itemId: "htshl",
                readOnly: false,
                mustInput: false,
                width: 150,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.00");
                },
            },
            {
                header: "备注",
                dataIndex: "remarks",
                itemId: "remarks",
                readOnly: false,
                mustInput: false,
                width: 250,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
        ],
        plugins: [
            Ext.create("Ext.grid.plugin.CellEditing", {
                clicksToEdit: 1,
            }),
        ],
    });
    //加到tab
    tabPanel.add(fb_cnt_jg);
    //提示
    // cnt_extend_grid.addDocked({ dock: 'top', xtype: 'label', html: '<span style="color:red;"> 温馨提示：<br/> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp 此页签数据从合同补充协议动态获取，无需填报。 </span>' });
    //自定义增行
    // var btn_add = Ext.create("Ext.button.Button", {
    //     itemId: "addrow_new",
    //     text: "甲供材物资增行",
    //     iconCls: "iconfont iconinsert-row",
    //     handler: function () { },
    // });
    // //加到工具栏
    // toolbar.insert(8, btn_add); //插入到第2个按钮前，从序号从0开始
    // let fb_cnt_jgStore = fb_cnt_jg.getStore();
    // btn_add.on("click", function () {
    //     fb_cnt_jgStore.add({
    //         phid: generateId(fb_cnt_jgStore.getCount() + 1).toString(),
    //     });
    // });

    // //自定义删行
    // var btn_del = Ext.create("Ext.button.Button", {
    //     itemId: "deleterow_new",
    //     text: "甲供材物资删行",
    //     iconCls: "iconfont icondelete-row",
    //     handler: function () { },
    // });
    // //加到工具栏
    // toolbar.insert(9, btn_del); //插入到第3个按钮前，从序号从0开始
    // btn_del.on("click", function () {
    //     let dataSelect = fb_cnt_jg.getSelectionModel().getSelection();
    //     fb_cnt_jgStore.remove(dataSelect);
    // });

    // if (otype == "view") {
    //     toolbar.get("addrow_new").setVisible(false);
    //     toolbar.get("deleterow_new").setVisible(false);
    // }
    //初始时，按钮不可见
    //  toolbar.get('addrow_new').setVisible(false);
    // toolbar.get('deleterow_new').setVisible(false)
}

function getExtendData() {
    ////甲供材物资
    var fb_cnt_jg = Ext.getCmp("fb_cnt_jg");
    var extendObj1 = fb_cnt_jg.getChange(false);
    //手动建立的表名
    return {
        fb_cnt_jg: JSON.stringify(extendObj1),
    };
}
